package com.quiz.quazz;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LaunchActivity extends Activity {
	private EditText editTextPlayerName;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_launch);

		editTextPlayerName = (EditText) findViewById(R.id.editText_player_name);
		editTextPlayerName.setText("test");

		Button buttonOpen = (Button) findViewById(R.id.button_open_game);
		Button buttonJoin = (Button) findViewById(R.id.button_join_game);

		buttonOpen.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				String playerName = editTextPlayerName.getText().toString();
				if (playerName != null && !playerName.isEmpty()) {
					LayoutInflater li = LayoutInflater.from(LaunchActivity.this);
					View promptsView = li.inflate(R.layout.prompt_port, null);

					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LaunchActivity.this);

					alertDialogBuilder.setView(promptsView);
					alertDialogBuilder.setMessage("Please enter the server port!");

					final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextInputPort);

					alertDialogBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							int port = Integer.parseInt(userInput.getText().toString());

							Intent intent = new Intent(LaunchActivity.this, LobbyActivity.class);
							intent.putExtra("isServer", true);
							intent.putExtra("serverPort", port);
							intent.putExtra("playerName", editTextPlayerName.getText().toString());
							startActivity(intent);
						}
					}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});

					AlertDialog alertDialog = alertDialogBuilder.create();

					alertDialog.show();
				} else {
					openToastNameEmpty();
				}
			}
		});
		buttonOpen.requestFocus();
		buttonJoin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				String playerName = editTextPlayerName.getText().toString();
				if (playerName != null && !playerName.isEmpty()) {
					Intent intent = new Intent(LaunchActivity.this, GameBrowserActivity.class);
					intent.putExtra("playerName", playerName);
					startActivity(intent);
				} else {
					openToastNameEmpty();
				}
			}

		});

	}

	private void openToastNameEmpty() {
		Toast toast = Toast.makeText(LaunchActivity.this, "Please enter a name!", Toast.LENGTH_SHORT);
		toast.show();
	}

}